<template>
  <div>
    <!-- 经销商账户查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhDealerAccountQuery"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
          :onSyncTableData="syncDataHandle"
        :mergeCellMethod="objectSpanMethod"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="exportHandler">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <BaseDialog :visible.sync="visible" title="余额锁定明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, exportExcel, getFiAccountType,exporturl } from '@/api/dealerFinanceP/MoneyManage/DealerAccountQuery';
import SonModel from './SonModel';
import { exportExcelFile } from '@/utils/index';

export default {
  name: 'DealerAccountQuery',
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      visible: false,
      isDealer: false,
      exportLoading: false
    };
  },
  components: {
    SonModel
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.accountType();
  },
  methods: {

    // 合并
    syncDataHandle(dataList) {
      if (!dataList.length) return;
      // 设定一个数组spanArr/contentSpanArr来存放要合并的格数，同时还要设定一个变量pos/position来记录
      this.spanArr1 = [];
      for (let i = 0; i < dataList.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          this.pos1 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1列)
          if (dataList[i].ownerCode === dataList[i - 1].ownerCode) {
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.push(1);
            this.pos1 = i;
          }

        }
      }
    },
    // 处理合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {

      if (column.property === 'ownerCode' || column.property === 'ownerName' || column.property === 'balanceAmountTotal') {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    selectChangeHandle(row) {},

    detailHandle(row) {
      this.visible = true;
      this.formData = row;
    },
    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 资金类型 getFiAccountType
    async accountType() {
      const res = await getFiAccountType({ ignoreAccountTypes: [60361001, 60361002] });
      if (res.resultCode === 200) {
        res.data.map(x => {
          this.topFilterList.find(item => item.fieldName == 'accountTypeId').itemList.push({ text: x.accountTypeName, value: x.id });
        });
      }
    },


    //测试
     // 处理合并单元格
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   console.log(row, column, rowIndex, columnIndex, '---奥利给---');
    //   if (column.property === 'ownerCode' || column.property === 'ownerName' || column.property === 'balanceAmount') {
    //     const _row = this.spanArr1[rowIndex];
    //     const _col = _row > 0 ? 1 : 0;
    //     return {
    //       rowspan: _row,
    //       colspan: _col
    //     };
    //   }
    // },

    // 导出
    async exportHandler() {
        let json = Object.assign({}, { CODE: 'CODE_00000231' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '经销商账户查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountTypeId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '账户状态',
          fieldName: 'status',
          placeholder: '请选择',
          itemList: this.createDictList('6058')
        },

        // {
        //   type: 'SELECT',
        //   label: '动力形式',
        //   fieldName: 'powerType',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('6008')
        // }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '经销商代码',
        //   dataIndex: 'ownerCode',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '经销商名称',
        //   dataIndex: 'ownerName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '账户名称',
        //   dataIndex: 'accountName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '账户总额',
          dataIndex: 'balanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        // {
        //   title: '欠款金额',
        //   dataIndex: 'amountInArear',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   precision: 2,
        //   numberFormat: true
        // },
        {
          title: '预扣',
          dataIndex: 'frozenAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true,
          render: props => {
            if (props.row.frozenAmount != 0) {
              return (
                <el-link type="warning" underline={true} onClick={() => this.detailHandle(props.row)}>
                  {props.row.frozenAmount}
                </el-link>
              );
            } else {
              return <span>{props.row.frozenAmount}</span>;
            }
          }
        },
        {
          title: '可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },


        // {
        //   title: '可用余额合计',  // 2021-2-25 14:41:36  店端没有可用余额合计字段
        //   dataIndex: 'vin',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: []
        // },

  {
          title: '可用余额合计',
          dataIndex: 'balanceAmountTotal',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true
        },




        {
          title: '三方已到期',
          dataIndex: 'ifExpireDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '账户状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6058'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '6058')}</span>;
          }
        },
        {
          title: '最后更新时间',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '授信单号',
        //   dataIndex: 'creditNo',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '项目编号',
        //   dataIndex: 'projectNo',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '有效起始日期',
        //   dataIndex: 'startTime',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range',
        //   dateFormat: 'yyyy-MM-dd'
        // },
        // {
        //   title: '有效截止日期',
        //   dataIndex: 'endTime',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'date-range',
        //   dateFormat: 'yyyy-MM-dd'
        // }
      ];
    }
  }
};
</script>
